package ntrees.hu.renren;


import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

import ntrees.hu.accounts.Constants;
import com.cooliris.media.R;

import android.accounts.Account;
import android.accounts.AccountAuthenticatorActivity;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

//https://graph.renren.com/oauth/authorize?client_id=fee11992a4ac4caabfca7800d233f814&response_type=token&redirect_uri=http://graph.renren.com/oauth/login_success.html

public class AuthActivity extends AccountAuthenticatorActivity {
	
	private String TAG = "AuthActivity";
	private String redirectUrl = "http://graph.renren.com/oauth/login_success.html";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		WebView wb = new WebView(this);
		ImageView iv = new ImageView(this);
		ProgressBar pb = new ProgressBar(this);
		iv.setImageResource(android.R.drawable.progress_horizontal);
		setContentView(R.layout.p_activity);
		
		
		wb.setVerticalScrollBarEnabled(false);
		wb.setHorizontalScrollBarEnabled(false);
		wb.getSettings().setJavaScriptEnabled(true);
		wb.setWebViewClient(client);
		wb.clearHistory();
		wb.requestFocus(View.FOCUS_DOWN);
		WebSettings setting = wb.getSettings();
		setting.setSavePassword(false);
		 CookieSyncManager.createInstance(this); 
		 CookieManager cookieManager = CookieManager.getInstance();
		 cookieManager.removeAllCookie();
		 cookieManager.setAcceptCookie(false);
		//wb.loadUrl("https://graph.renren.com/oauth/authorize?client_id=b2585844587c491f89a5303ac23a119d&response_type=token&redirect_uri=http://graph.renren.com/oauth/login_success.html");
	   wb.loadUrl("https://graph.renren.com/oauth/authorize?display=touch&scope=publish_feed+create_album+photo_upload+read_user_album+read_user_photo+status_update&response_type=token&client_id=b2585844587c491f89a5303ac23a119d&redirect_uri=http%3A%2F%2Fgraph.renren.com%2Foauth%2Flogin_success.html");
	}
	
	String mUsername, mPassword;
    protected void finishConfirmCredentials(boolean result) {
        Log.i(TAG, "finishConfirmCredentials()");
        //mUsername = "testName";
        mPassword = "testPassword";
        
        final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);
        AccountManager mAccountManager = AccountManager.get(this);
        //mAccountManager.setPassword(account, mPassword);
        mAccountManager.addAccountExplicitly(account, mPassword, null);
        final Intent intent = new Intent();
        intent.putExtra(AccountManager.KEY_BOOLEAN_RESULT, result);
        setAccountAuthenticatorResult(intent.getExtras());
        setResult(RESULT_OK, intent);
        Log.d(TAG, "intent: " + intent.toString());
        finish();
    }
    
    class SessionKeyThread extends Thread {
    	String token;
    	
    	SessionKeyThread(String authToken) {
    		token = authToken;
    	}
    	public void run() {
    		//SessionKeyManager skm = new SessionKeyManager();
    		Looper.getMainLooper().prepare();
    		AccessTokenManager mAccessTokenManager = AccessTokenManager.getInstance(AuthActivity.this);
    		mAccessTokenManager.updateAccessToken(token);
    		Log.d(TAG, "user: " + mAccessTokenManager.getUid());
    		mUsername = String.valueOf(mAccessTokenManager.getUid());
    		Toast.makeText(AuthActivity.this, String.valueOf(mAccessTokenManager.getUid()), Toast.LENGTH_LONG).show();
    		finishConfirmCredentials(true);
    	}
    }
	
	WebViewClient client =  new WebViewClient() {

		@Override
		public void onLoadResource(WebView view, String url) {
			// TODO Auto-generated method stub
			super.onLoadResource(view, url);
			Log.d(TAG, "onLoadResource");
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			super.onPageFinished(view, url);
			Log.d(TAG, "onPageFinished: " + view.getUrl());
			//view.getUrl();
			setContentView(view);
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			// TODO Auto-generated method stub
			Log.d(TAG, "onPageStarted: " + url);
            if (url.startsWith(redirectUrl)) {
                Bundle values = parseUrl(url);
                String accessToken = values.getString("access_token");
                if (accessToken != null) {
                	Log.d(TAG, "login ok");
                	Log.d(TAG, values.toString());
                	Toast.makeText(AuthActivity.this, "登录成功！", Toast.LENGTH_LONG).show();
                	//Intent it = new Intent();
                	//it.putExtras(values);
                	//AuthActivity.this.setResult(Activity.RESULT_OK, it);
                	//finish();
                	new SessionKeyThread(accessToken).start();
                	return;
                }
            }
            super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			// TODO Auto-generated method stub
			super.onReceivedError(view, errorCode, description, failingUrl);
			Log.d(TAG, "onReceivedError, " + description);
		}

		@Override
		public void onReceivedSslError(WebView view,
				SslErrorHandler handler, SslError error) {
			// TODO Auto-generated method stub
			super.onReceivedSslError(view, handler, error);
			Log.d(TAG, "onReceivedSslError");
		}
	};
	
    /**
     * 解析URL中的查询串转换成key-value
     * 
     * @param url
     * @return
     */
    public static Bundle parseUrl(String url) {
        url = url.replace("rrconnect", "http");
        url = url.replace("#", "?");
        try {
            URL u = new URL(url);
            Bundle b = decodeUrl(u.getQuery());
            b.putAll(decodeUrl(u.getRef()));
            return b;
        } catch (MalformedURLException e) {
            return new Bundle();
        }
    }
    
    /**
     * 将用&号链接的URL参数转换成key-value形式。
     * 
     * @param s
     * @return
     */
    public static Bundle decodeUrl(String s) {
        Bundle params = new Bundle();
        if (s != null) {
            params.putString("url", s);
            String array[] = s.split("&");
            for (String parameter : array) {
                String v[] = parameter.split("=");
                if (v.length > 1) {
                    params.putString(v[0], URLDecoder.decode(v[1]));
                }
            }
        }
        return params;
    }
}
